package com.example.myapplication;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Toast;

import androidx.fragment.app.Fragment;
import com.example.myapplication.databinding.ChooseAreaBinding;
import com.example.myapplication.db.City;
import com.example.myapplication.db.County;
import com.example.myapplication.db.Province;
import com.example.myapplication.util.Httputil;
import com.example.myapplication.util.Utility;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

import org.jetbrains.annotations.NotNull;
import org.litepal.LitePal;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ChooseAreaFragment extends Fragment {
    private static final String PROVINCE_URL = "http://guolin.tech/api/china";
    ChooseAreaBinding binding;
    /** 根据级别不同，显示不同列表数据，如果级别为0，则显示省份列表 */
    public static final int LEVEL_PROVINCE = 0;
    public static final int LEVEL_CITY = 1;
    public static final int LEVEL_COUNTY = 2;
    private int currentLevel = LEVEL_PROVINCE;
    private Province selectedProvince;
    private City selectedCity;
    List<Province> provinceList;
    List<City> cityList;
    List<County> countyList;

    List<String> dataList = new ArrayList<>(); // 列表数据
    ArrayAdapter<String> adapter; // 列表组件所需的适配器组件

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = ChooseAreaBinding.inflate(inflater, container, false);
        adapter = new ArrayAdapter<>(getActivity(), android.R.layout.simple_list_item_1, dataList);
        binding.listView.setAdapter(adapter);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        binding.listView.setOnItemClickListener((adapterView, view, position, id) -> {
            if (currentLevel == LEVEL_PROVINCE) {
                selectedProvince = provinceList.get(position);
                queryCities();
            } else if (currentLevel == LEVEL_CITY) {
                selectedCity = cityList.get(position);
                queryCounties();
            }
        });
        binding.backButton.setOnClickListener(v -> {
            if (currentLevel == LEVEL_CITY) {
                queryProvinces();
            } else if (currentLevel == LEVEL_COUNTY) {
                queryCities();
            }
        });
        queryProvinces();
    }

    private void queryCities() {
        binding.titleText.setText(selectedProvince.getProvinceName());
        binding.backButton.setVisibility(View.VISIBLE);
        cityList = LitePal.where("provinceId = ?", String.valueOf(selectedProvince.getId())).find(City.class);
        if (cityList.size() > 0) {
            // 从数据库中获取数据
            dataList.clear(); // 清除原来的所有数据
            cityList.forEach((item) -> {
                dataList.add(item.getCityName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_CITY;
        } else {
            // 数据库中没有数据，从服务器获取
            String url = PROVINCE_URL + "/" + selectedProvince.getProvinceCode();
            queryFromServer(url, "city");
        }
    }

    private void queryProvinces() {
        binding.titleText.setText("中国(China)");
        binding.backButton.setVisibility(View.GONE);
        provinceList = LitePal.findAll(Province.class);
        if (provinceList.size() > 0) {
            // 从数据库中获取数据
            dataList.clear(); // 清除原来的所有数据
            provinceList.forEach((item) -> {
                dataList.add(item.getProvinceName());
            });
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_PROVINCE;
        } else {
            // 数据库中没有数据，从服务器获取
            queryFromServer(PROVINCE_URL, "province");
        }
    }

    private void queryCounties() {
        binding.titleText.setText(selectedCity.getCityName());
        binding.backButton.setVisibility(View.VISIBLE);

        countyList = LitePal.where("cityid=?", String.valueOf(selectedCity.getId()))
                .find(County.class);
        if (countyList.size() > 0) {
            dataList.clear();
            for (County county : countyList) {
                dataList.add(county.getCountName());
            }
            adapter.notifyDataSetChanged();
            binding.listView.setSelection(0);
            currentLevel = LEVEL_COUNTY;
        } else {
            int provinceCode = selectedProvince.getProvinceCode();
            int cityCode = selectedCity.getCityCode();
            String address = "http://guolin.tech/api/china/" + provinceCode + "/" + cityCode;
            queryFromServer(address, "county");
        }
    }

    private void queryFromServer(String url, String type) {
        Httputil.sendOkHttpRequest(url, new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                getActivity().runOnUiThread(() -> {
                    Toast.makeText(getContext(), "访问网络失败", Toast.LENGTH_SHORT).show();
                });
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                String strJson = response.body().string();
                boolean result = false;
                if ("province".equals(type)) {
                    result = Utility.handleProvinceResponse(strJson);
                } else if ("city".equals(type)) {
                    result = Utility.handleCityResponse(strJson, selectedProvince.getId());
                } else if ("county".equals(type)) {
                    result = Utility.handleCountyResponse(strJson, selectedCity.getId());
                }
                if (result) {
                    if ("province".equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryProvinces();
                        });
                    } else if ("city".equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryCities();
                        });
                    } else if ("county".equals(type)) {
                        getActivity().runOnUiThread(() -> {
                            queryCounties();
                        });
                    }
                }
            }
        });
    }
}

